package com.javatian.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.javatian.common.Result;
import com.javatian.common.ResultCode;
import com.javatian.entity.*;
import com.javatian.exception.CustomException;
import com.javatian.service.AdminInfoService;
import com.javatian.service.UserInfoService;
import com.javatian.service.WorkerInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 账号相关的控制器
 */
@RestController
public class AccountController {

    //权限列表
    @Value("${authority.info}")
    private String authorityStr;

    //用户信息
    @Value("${const.user}")
    private String user;


    @Autowired
    private AdminInfoService adminInfoService;

    @Autowired
    private WorkerInfoService workerInfoService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 获取权限列表
     * @return
     */

    @GetMapping("/getAuthority")
    public Result<List<AuthorityInfo>> getAuthority(){
        List<AuthorityInfo> authorityInfoList = JSONUtil.toList(JSONUtil.parseArray(authorityStr), AuthorityInfo.class);
        return Result.success(authorityInfoList);
    }

    /**
     * 根据账号和密码登录
     */
    @PostMapping("/login")
    public Result<Account> login(@RequestBody Account account, HttpServletRequest request){
       if (StrUtil.isBlank(account.getName())||StrUtil.isBlank(account.getPassword())||account.getLevel()==null){
           throw new CustomException(ResultCode.PARAM_LOST_ERROR);
       }
       Integer level = account.getLevel();
        Account login = new Account();
        if (1==level){
            login = adminInfoService.login(account.getName(), account.getPassword());
        }
        if (2==level){
            login = workerInfoService.login(account.getName(), account.getPassword());
        }
        if (3==level){
            login = userInfoService.login(account.getName(), account.getPassword());
        }
        request.getSession().setAttribute(user,login);
        return Result.success(login);

    }

    /**
     * 查询用户是否已经登录，如果已经登录，返回用户信息
     */

    @GetMapping("/auth")
    public Result auth(HttpServletRequest request){
        Object obj = request.getSession().getAttribute(user);
        if (obj == null){
            return Result.error("401","未登录");
        }
        return Result.success(obj);
    }

    /**
     * 退出
     */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        request.getSession().setAttribute(user,null);
        return Result.success();
    }

    /**
     * 获取当前用户所能看到的模块信息
     */
    @GetMapping("/authority")
    public Result<List<Integer>> authority(HttpServletRequest request){
        Account account = (Account) request.getSession().getAttribute(user);
        if (account == null){
            return Result.success(new ArrayList<>());
        }
        JSONArray objects = JSONUtil.parseArray(authorityStr);
        for (Object object:objects){
            JSONObject jsonObject =(JSONObject) object;
            if (account.getLevel().equals(jsonObject.getInt("level"))){
                JSONArray array = JSONUtil.parseArray(jsonObject.getStr("models"));
                List<Integer> modelIdList = array.stream().map((o -> {
                    JSONObject obj = (JSONObject) o;
                    return obj.getInt("modelId");
                })).collect(Collectors.toList());
                return Result.success(modelIdList);
            }
        }
        return Result.success(new ArrayList<>());
    }

    /**
     * 根据姓名查--test
     */
    @GetMapping("/findByUserName/{username}")
    public Result<AdminInfo> findByUserName(@PathVariable String username){
        AdminInfo adminInfo = adminInfoService.findByUserName(username);
        return Result.success(adminInfo);

    }
    /**
     * 获取当前页面的权限列表
     */
    @GetMapping("/permission/{modelId}")
    public Result<List<Integer>> permission(@PathVariable Integer modelId,HttpServletRequest request){
        Account account = (Account) request.getSession().getAttribute(user);
        if (account == null){
            return Result.success(new ArrayList<>());
        }
        JSONArray objects = JSONUtil.parseArray(authorityStr);
        List<AuthorityInfo> authorityInfoList = JSONUtil.toList(objects, AuthorityInfo.class);
        Optional<AuthorityInfo> optional = authorityInfoList.stream().filter(x -> x.getLevel().equals(account.getLevel())).findFirst();
        if (optional.isPresent()){
            Optional<AuthorityInfo.Model> optional1 = optional.get().getModels().stream().filter(x -> x.getModelId().equals(modelId)).findFirst();
            if (optional1.isPresent()){
                List<Integer> list = optional1.get().getOperation();
                return Result.success(list);
            }
        }
        return Result.success(new ArrayList<>());
    }

    /**
     * 注册新账号
     */
    @PostMapping("/register")
    public Result<Account> register(@RequestBody Account account,HttpServletRequest request){
        Integer level = account.getLevel();
        Account login = new Account();
        if (level == 2){                 //工作人员注册
            WorkerInfo workerInfo = new WorkerInfo();
            BeanUtils.copyProperties(account,workerInfo);
            login = workerInfoService.add(workerInfo);
        }
        if (level == 3){                //普通用户注册
            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(account,userInfo);
            userInfoService.add(userInfo);
        }
        request.getSession().setAttribute(user,login);
        return Result.success(login);

    }

    /**
     * 获取当前登录用户的个人信息
     */
    @GetMapping("/getAccountInfo")
    public Result<Object> getAccountInfo(HttpServletRequest request){
        Account account = (Account) request.getSession().getAttribute(user);
        if (account == null){
            return Result.success(new Object());
        }
        Integer level = account.getLevel();
        if(level == 1){
            return Result.success(adminInfoService.findById(account.getId()));
        }
        if(level == 2){
            return Result.success(workerInfoService.findById(account.getId()));
        }
        if(level == 3){
            return Result.success(userInfoService.findById(account.getId()));
        }
        return Result.success(new Object());
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account info,HttpServletRequest request){
        Account account = (Account) request.getSession().getAttribute(user);
        if (account == null){
            return Result.error(ResultCode.USER_NOT_EXIST_ERROR.code,ResultCode.USER_NOT_EXIST_ERROR.msg);
        }
        String oldPassword = SecureUtil.md5(info.getPassword());
        if (!oldPassword.equals(account.getPassword())){
            return Result.error(ResultCode.PARAM_PASSWORD_ERRO.code,ResultCode.PARAM_PASSWORD_ERRO.msg);
        }
        info.setPassword(SecureUtil.md5(info.getNewPassword()));
        Integer level = account.getLevel();
        if (level == 1){
            AdminInfo adminInfo = new AdminInfo();
            BeanUtils.copyProperties(info,adminInfo);
            adminInfoService.update(adminInfo);
        }
        if (level == 2){
            WorkerInfo workerInfo = new WorkerInfo();
            BeanUtils.copyProperties(info,workerInfo);
            workerInfoService.update(workerInfo);
        }
        if (level == 3){
            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(info,userInfo);
            userInfoService.update(userInfo);
        }
        request.getSession().setAttribute(user,null);
        return Result.success();
    }


















}
